import express from 'express';
const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));

let books = [
    {id:1,title:'平凡的世界',author:'余华'},
    {id:2,title:'狼王梦',author:'沈石溪'},
    {id:3,title:'红楼梦',author:'曹雪芹'}
];

//获取所有书籍
app.get('/books',(req,res)=>{
    res.json(books);
})

//添加书籍
app.post('/books',(req,res)=>{
    const newBook = {
        id:books.length + 1,
        title:req.body.title,
        author: req.body.author
    };
    books.push(newBook);
    res.status(201).json(newBook);
})

// 更新
app.put('/books/:id', (req, res) => {
    const bookId = parseInt(req.params.id);
    const bookIndex = books.findIndex(book => book.id === bookId);
    if (bookIndex >= 0) {
      books[bookIndex] = {
        ...books[bookIndex],
        title: req.body.title,
        author: req.body.author
      };
      res.json(books[bookIndex]);
    } else {
      res.status(404).send('没有找到图书');
    }
  });
  
  // 删除
  app.delete('/books/:id', (req, res) => {
    const bookId = parseInt(req.params.id);
    const bookIndex = books.findIndex(book => book.id === bookId);
    if (bookIndex >= 0) {
      books = books.filter(book => book.id !== bookId);
      res.status(204).send();
    } else {
      res.status(404).send('没有找到图书');
    }
  });

const port = 3000;
app.listen(port,()=>{
    console.log(`server running at http://localhost:${port}`);
    
})
